package Concurrent;

import java.util.Collections;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Description：
 * Author: zhangc
 * Date：2017/9/29 20:30
 */
public class CyclicBarrierTest {

    private static final CyclicBarrier barrier = new CyclicBarrier(5, new Runnable() {
        @Override
        public void run() {
            int sum = 0;
            while (!queue.isEmpty())
                sum += queue.remove();
            System.out.println(sum);
        }
    });
    private static final ExecutorService executor = Executors.newFixedThreadPool(10);
    public static AtomicInteger atomicInteger = new AtomicInteger(0);
    public static final Queue<Integer> queue = new ConcurrentLinkedQueue<>();

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            executor.execute(new Worker(barrier));
            if (i == 5)
                barrier.reset();
        }
        executor.shutdown();
    }

}

class Worker implements Runnable {
    private CyclicBarrier cyclicBarrier;

    public Worker(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        try {
            CyclicBarrierTest.queue.add(CyclicBarrierTest.atomicInteger.incrementAndGet());
            Thread.sleep(new Random().nextInt(5) * 1000);
            cyclicBarrier.await();// 执行完了之后 插入屏障
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}
